package cn.lbf.stuniversity.equipmenttype.service;

import cn.lbf.stuniversity.equipmenttype.dao.EquipmentTypeDao;
import cn.lbf.stuniversity.equipmenttype.entity.EquipmentType;
import cn.lbf.stuniversity.equipmenttype.entity.EquipmentTypeTreeNode;
import cn.lbf.stuniversity.equipmenttype.form.EquipTypeAddForm;
import cn.lbf.stuniversity.equipmenttype.form.EquipTypeDetailForm;
import cn.lbf.stuniversity.equipmenttype.form.EquipTypeForm;
import cn.lbf.stuniversity.utils.PageUtil;
import cn.lbf.stuniversity.vo.PageVO;
import cn.lbf.stuniversity.vo.Result;
import cn.lbf.stuniversity.utils.ResultUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.lbf.stuniversity.constant.Code;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.data.domain.Page;


@Service
public class EquipmentTypeServiceImpl implements EquipmentTypeService{

    @Autowired
    private EquipmentTypeDao equipmentTypeDao;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String,Object>> addNew(EquipTypeAddForm equipTypeAddForm) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("equipmentTypeId",equipTypeAddForm.getEquipmentTypeId());
        map.put("equipmentTypeName",equipTypeAddForm.getEquipmentTypeName());
        int EquipCount=equipmentTypeDao.selectEquipTypeCountByIdAndName(map);
        if(EquipCount>0){//如果查詢出來有同名的分類
            return new ResultUtil<Map<String, Object>>().setErrorMsg(Code.HAS_EXISTS, "已有同名的分类!");
        }
        int i = equipmentTypeDao.addNew(equipTypeAddForm);
        if(i>0){
            return new ResultUtil<Map<String, Object>>().setSuccessMsg("添加成功");
        }else{
            return new ResultUtil<Map<String, Object>>().setErrorMsg(Code.FAIL, "添加失败，请联系管理员!");
        }
    }

    @Override
    public List<EquipmentType> selectAll() {
        return equipmentTypeDao.selectAll();
    }

    @Override
    @Transactional(readOnly = true)
    public Result<Page<EquipmentType>> queryList(EquipTypeForm form){
        // 1. 先查询数据（XML已经处理了分页）
        try{
            form.initOffSet();//
            List<EquipmentType> list = equipmentTypeDao.selectEquipTypeByIdAndName(form);
            long count = equipmentTypeDao.queryCount(form);
            PageVO pageVO = new PageVO(form.getPageNumber(), form.getPageSize());
            PageImpl<EquipmentType> page = new PageImpl<>(list, PageUtil.initPage(pageVO), count);
            return new ResultUtil<Page<EquipmentType>>().setData(page);
        }catch (Exception e){
            e.printStackTrace();
            return new ResultUtil<Page<EquipmentType>>().setErrorMsg("查询有误 请联系管理员");
        }
    }

    @Override
    public Result<String> del(String equipmentTypeId){
        EquipmentType equipmentType = equipmentTypeDao.selectById(equipmentTypeId);
        if(equipmentType==null){
            return new ResultUtil<String>().setErrorMsg(Code.NOT_EXISTS, "分类不存在");
        }
        int remove = equipmentTypeDao.deleteByUpdateId(equipmentTypeId);
        if (remove > 0) {
            return new ResultUtil<String>().setSuccessMsg("删除成功");
        }else {
            return new ResultUtil<String>().setErrorMsg(Code.FAIL,"删除失败 请联系管理员");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> updateByEquipmentTypeId(EquipTypeDetailForm equipTypeDetailForm) {
        EquipmentType equipmentType = equipmentTypeDao.selectById(equipTypeDetailForm.getEquipmentTypeId());
        if(equipmentType ==null){
            return new ResultUtil<String>().setErrorMsg(Code.FAIL,"更新失败 查无此设备");
        }
        int updateNum = equipmentTypeDao.updateByEquipmentTypeId(equipTypeDetailForm);
        if (updateNum > 0) {
            return new ResultUtil<String>().setSuccessMsg("更新成功!");
        }
        return new ResultUtil<String>().setErrorMsg("更新失败!");
    }

    @Override
    public List<EquipmentTypeTreeNode> getEquipmentTypeTree() {
        List<EquipmentType> allEquipmentTypes = equipmentTypeDao.selectAllEquipmentTypes();
        Map<String, EquipmentTypeTreeNode> nodeMap = new HashMap<>();
        List<EquipmentTypeTreeNode> rootNodes = new ArrayList<>();

        // 构建节点映射表
        for (EquipmentType equipmentType : allEquipmentTypes) {
            EquipmentTypeTreeNode node = new EquipmentTypeTreeNode(equipmentType);
            nodeMap.put(equipmentType.getEquipmentTypeId(), node);
        }

        // 构建树结构
        for (EquipmentType equipmentType : allEquipmentTypes) {
            if (equipmentType.getLev() == 1) {
                rootNodes.add(nodeMap.get(equipmentType.getEquipmentTypeId()));
            } else {
                String parentId = calculateParentId(equipmentType, allEquipmentTypes);
                EquipmentTypeTreeNode parentNode = nodeMap.get(parentId);
                if (parentNode != null) {
                    parentNode.getChildren().add(nodeMap.get(equipmentType.getEquipmentTypeId()));
                }
            }
        }

        return rootNodes;
    }

    private String calculateParentId(EquipmentType equipmentType, List<EquipmentType> allEquipmentTypes) {
        // 根据业务逻辑计算父节点 ID
        // 例如，假设父节点的 lev 比当前节点少 1
        for (EquipmentType parent : allEquipmentTypes) {
            if (parent.getLev() == equipmentType.getLev() - 1) {
                return parent.getEquipmentTypeId();
            }
        }
        return null;
    }

}
